//
//  TakePhotoView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/21.
//

import SwiftUI
import AVFoundation
import Photos

struct TakePhotoView: View {
    @StateObject private var camera = CameraManager()
    @State private var capturedImage: UIImage?
    @EnvironmentObject var appState: AppState
    @StateObject var viewModel = DeviceDetailVM()
    @State private var showImagePicker = false
    @State private var sourceType: UIImagePickerController.SourceType = .photoLibrary
    @State private var selectedImage: UIImage?
    var body: some View {
        VStack {
            CustomNavigationBar(rightImageName: nil, title: "拍照控制") {}
            CameraPreview(session: camera.session)
            HStack() {
                if let image = capturedImage {
                    Image(uiImage: image)
                        .resizable()
                        .scaledToFit()
                        .frame(width: 40,height: 60)
                        .onTapGesture {
                            //跳转到相册
                            if let url = URL(string: "photos-redirect://") {
                                UIApplication.shared.open(url)
                            }
                            // checkPhotoLibraryPermission()
                        }
                }else {
                    Image("")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 40,height: 60)
                }
               
                Spacer()
                Button(action: {
                    camera.capturePhoto { image in
                        capturedImage = image
                        camera.saveToAlbum(image: image) { success in
                            if success {
                                viewModel.takePhoteAction = 0
                            }
                        }
                    }
                }) {
                    Image("拍照")
                        .resizable()
                        .frame(width: 45, height: 45)
                }
                
                Spacer()
                
                Button(action: {
                    camera.switchCamera()
                }) {
                    Image("相机翻转")
                        .resizable()
                        .frame(width: 30, height: 30)
                }
            }
            .frame(height: 60)
            .padding(.horizontal,18)
            .padding(.bottom,30)
            .sheet(isPresented: $showImagePicker) {
                ImagePickerView(sourceType: sourceType, selectedImage: $selectedImage)
            }
            .onChange(of: viewModel.takePhoteAction) {newValue in
                if newValue == 2 {
                    camera.capturePhoto { image in
                        DispatchQueue.main.async {
                            capturedImage = image
                            camera.saveToAlbum(image: image) { success in
                                DispatchQueue.main.async {
                                    viewModel.takePhoteAction = 0
                                }
                            }
                        }
                    }
                }else if newValue == 3 {
                    DispatchQueue.main.async {
                        viewModel.takePhoteAction = 0
                        appState.navigateBack()
                    }
                }
            }
        }
        .navigationBarHidden(true)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
        .onAppear {
            viewModel.setCameraStatus(eventCode: 1)
            camera.startSession()
        }
        .onDisappear{
            viewModel.setCameraStatus(eventCode: 2)
        }
    }
    
    
    private func checkPhotoLibraryPermission() {
        let status = PHPhotoLibrary.authorizationStatus()
        switch status {
        case .authorized:
            sourceType = .photoLibrary
            showImagePicker = true
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { newStatus in
                DispatchQueue.main.async {
                    if newStatus == .authorized {
                        sourceType = .photoLibrary
                        showImagePicker = true
                    } else {
                        showImagePicker = false
                    }
                }
            }
        default:
            showImagePicker = false
        }
    }
}


struct CameraPreview: UIViewRepresentable {
    let session: AVCaptureSession
    
    func makeUIView(context: Context) -> UIView {
        let view = UIView()
        let previewLayer = AVCaptureVideoPreviewLayer(session: session)
        previewLayer.videoGravity = .resizeAspectFill
        view.layer.addSublayer(previewLayer)
        return view
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        DispatchQueue.main.async {
            (uiView.layer.sublayers?.first as? AVCaptureVideoPreviewLayer)?.frame = uiView.bounds
        }
    }
}

class CameraManager: NSObject, ObservableObject {
    let session = AVCaptureSession()
    private let photoOutput = AVCapturePhotoOutput()
    private var captureCompletion: ((UIImage) -> Void)?
    private let sessionQueue = DispatchQueue(label: "camera.session.queue")
    private var currentCameraPosition: AVCaptureDevice.Position = .back

    override init() {
        super.init()
        setupCamera()
    }
    
    func checkPermissions() {
        switch AVCaptureDevice.authorizationStatus(for: .video) {
            case .notDetermined:
                AVCaptureDevice.requestAccess(for: .video) { _ in
                    self.startSession()
                }
            case .authorized:
                startSession()
            default: break
        }
    }
    
    
    func startSession() {
        sessionQueue.async {
            self.session.startRunning()
        }
    }
    
    func setupCamera() {
        sessionQueue.async {
            self.session.sessionPreset = .photo
            guard let device = AVCaptureDevice.default(.builtInWideAngleCamera,
                                                       for: .video, position: self.currentCameraPosition),
                  let input = try? AVCaptureDeviceInput(device: device) else { return }
            
            self.session.beginConfiguration()
            self.session.inputs.forEach { self.session.removeInput($0) }
            
            if self.session.canAddInput(input) {
                self.session.addInput(input)
            }
            if self.session.canAddOutput(self.photoOutput) {
                self.session.addOutput(self.photoOutput)
            }
            self.session.commitConfiguration()
        }
    }
    
    func switchCamera() {
        sessionQueue.async {
            self.currentCameraPosition = self.currentCameraPosition == .back ? .front : .back
            self.setupCamera()
        }
    }
    
    func capturePhoto(completion: @escaping (UIImage) -> Void) {
        self.captureCompletion = completion
        let settings = AVCapturePhotoSettings()
        sessionQueue.async {
            self.photoOutput.capturePhoto(with: settings, delegate: self)
        }
    }
    
    func saveToAlbum(image: UIImage,completion: @escaping (Bool) -> Void) {
        PHPhotoLibrary.requestAuthorization { status in
            guard status == .authorized else { return }
            PHPhotoLibrary.shared().performChanges {
                PHAssetChangeRequest.creationRequestForAsset(from: image)
                completion(true)
            }
        }
    }
}

extension CameraManager: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput,
                     didFinishProcessingPhoto photo: AVCapturePhoto,
                     error: Error?) {
        guard let data = photo.fileDataRepresentation(),
              let image = UIImage(data: data) else { return }
        // 如果是前置摄像头拍摄的照片，需要镜像处理
        var finalImage = image
        if self.currentCameraPosition == .front {
            finalImage = UIImage(cgImage: image.cgImage!, scale: image.scale, orientation: .leftMirrored)
        }
        DispatchQueue.main.async {
            self.captureCompletion?(finalImage)

        }
    }
}
